﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCMS.CoreBusinessLogic.Web;
using SCMS.Model;
using SCMS.CoreBusinessLogic;
using SCMS.CoreBusinessLogic._Item;
using SCMS.UI.Models;
using SCMS.CoreBusinessLogic.Security;
using SCMS.CoreBusinessLogic.ActionFilters;
using System.Data.Objects.DataClasses;
using SCMS.UI.GeneralHelper;

namespace SCMS.UI.Controllers
{
    public class ItemController : PortalBaseController
    {
        private IItemService itemService;

        public ItemController(IPermissionService permissionService, IUserContext userContext, IItemService _itemService)
            : base(userContext, permissionService)
        {
            this.itemService = _itemService;
        }

        //
        // GET: Index
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: CreateEdit
        public ActionResult CreateEdit(string iid)
        {
            UItem item = new UItem();

            item.ItemCatSelect =
                new SelectList(itemService.ItemCatObj.GetItemCategories(), "Id", "CategoryName");

            item.ItemClassSelect = new SelectList(itemService.ItemClassObj.GetItemClassifications(countryProg.Id), "Id", "Name");

            item.ItemUnitsSelect = new SelectList(itemService.ItemClassObj.GetUnitOfMessures(countryProg.Id), "Id", "Code");

            Guid iId;
            if (Guid.TryParse(iid, out iId))
            {
                ViewBag.Action = "Edit";
                item._item = itemService.GetItem(iId);
            }

            ViewBag.Inventory = false;
            if (Request["Inventory"] != null)
            {
                ViewBag.Inventory = true;
            }

            return View(item);
        }

        //
        // POST: CreateEdit
        [HttpPost]
        public ActionResult CreateEdit(UItem item, string Action = "")
        {
            if (ModelState.IsValid)
            {
                if (Action.Equals("Edit"))
                {
                    item._item.CountryProgrammeId = countryProg.Id;
                    if (itemService.EditItem(item._item))
                    {
                        ModelState.Clear();
                        item = new UItem();
                        ViewBag.Message = "Item edited !";
                    }
                    else
                    {
                        ViewBag.Error = "Item not edited, please try again !";
                    }
                }
                else
                {
                    item._item.CountryProgrammeId = countryProg.Id;
                    if (itemService.AddItem(item._item))
                    {
                        ModelState.Clear();
                        item = new UItem();
                        ViewBag.Message = "Item added!";
                    }
                    else
                    {
                        ViewBag.Error = "Item not added, please try again !";
                    }
                }
            }
            return RedirectToAction("ListView");
        }

        //
        // GET: ListView
        public ActionResult ListView(string search = "")
        {
            using (var dbContext = new SCMSEntities())
            {
                List<viewItems> itmz = new List<viewItems>();
                foreach (Model.Item item in dbContext.Items.Where(p => p.CountryProgrammeId == countryProg.Id).ToList())
                {
                    ItemCategory ic = item.ItemCategory;
                    ItemClassification ics = item.ItemClassification;
                    itmz.Add(new viewItems() { item = item, pack = item.ItemPackages.ToList() });
                }
                return View(itmz);
            }
        }

        //
        // GET: DeleteItem
        public ActionResult DeleteItem(string iid)
        {
            Guid iId;
            if (Guid.TryParse(iid, out iId))
            {
                if (itemService.DeleteItem(iId))
                {
                    ModelState.Clear();
                    ViewBag.Message = "Item delete successfull !";
                }
                else
                {
                    ViewBag.Error = "Item not deleted, please try again !";
                }
            }
            else
            {
                ViewBag.Error = "No Item deleted !";
            }
            return RedirectToAction("ListView");
        }

        public ActionResult DeletePack(Guid pkgId)
        {
            if (itemService.DeletePack(pkgId))
            {
                ModelState.Clear();
                ViewBag.Message = "Item delete successfull !";
            }
            else
            {
                ViewBag.Error = "Item not deleted, please try again !";
            }
            return RedirectToAction("ListView");
        }

        public ActionResult CreateEditItemPackage(Guid? pkgId)
        {
            using (var db = new SCMSEntities())
            {
                ItemPack model = new ItemPack();
                if (pkgId.IsNullOrEmpty())
                    model.EntityItemPackage = new ItemPackage();
                else { model.EntityItemPackage = db.ItemPackages.FirstOrDefault(p => p.Id == pkgId); ViewBag.Action = "Edit"; }
                model.Items = new SelectList(itemService.GetItems(countryProg.Id), "Id", "Name");
                return View(model);
            }
        }

        [HttpPost]
        public ActionResult CreateEditItemPackage(ItemPack model, string Action = "")
        {
            if (ModelState.IsValid)
            {
                if (Action.Equals("Edit"))
                {
                    if (itemService.EditPackage(model.EntityItemPackage))
                    {
                        ModelState.Clear();
                        model.EntityItemPackage = new ItemPackage();
                        ViewBag.Message = "package edited !";
                    }
                    else
                    {
                        ViewBag.Error = "package not edited, please try again !";
                    }
                }
                else
                {
                    model.EntityItemPackage.Id = Guid.NewGuid();
                    if (itemService.AddPackage(model.EntityItemPackage))
                    {
                        ModelState.Clear();
                        model.EntityItemPackage = new ItemPackage();
                        ViewBag.Message = "package added!";
                    }
                    else
                    {
                        ViewBag.Error = "package not added, please try again !";
                    }
                }
            }
            return RedirectToAction("ListView");
        }

        public ActionResult SearchItems()
        {
            string searchTerm = Request.QueryString["q"];
            if (UserSession.CurrentSession.ItemList == null)
                UserSession.CurrentSession.ItemList = itemService.GetItems(countryProg.Id);
            string searchResults = "";
            foreach (Item item in UserSession.CurrentSession.ItemList)
            {
                if (item.Name.StartsWith(searchTerm, true, System.Globalization.CultureInfo.CurrentCulture))
                    searchResults += item.Name + "\n";
            }
            searchResults = searchResults != "" ? searchResults : "\n";
            return Content(searchResults, "text/html");
        }
    }
}
